package com.noahplat.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.noahplat.common.utils.Result;
import com.noahplat.common.utils.StatusCode;
import com.noahplat.user.mapper.*;
import com.noahplat.user.pojo.*;
import com.noahplat.user.service.MenuService;
import com.noahplat.user.utils.MenuDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 菜单栏相关接口
 *
 * @author 李东
 * @version 1.0.0
 * @Date: 2021/2/27 13:28
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private SysTypeMapper sysTypeMapper;

    @Autowired
    private AccountMapper accountMapper;

    /**
     * 查询菜单列表
     *
     * @author 李东
     * @version 1.0.0
     * @Date: 2021/2/27 13:28
     */
    @Override
    public Result getMenuList(String systype, Long uid) {
        //查询用户相关权限信息
        Example roleEmp = new Example(UserRole.class);
        roleEmp.createCriteria().andEqualTo("uid", uid);
        List<UserRole> userRoleList = userRoleMapper.selectByExample(roleEmp);
        if (ObjectUtils.isEmpty(userRoleList)) {
            return new Result(true, StatusCode.ACCESSERROR, "权限认证失败！");
        }
        //查询当前权限关联的菜单栏
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        for (UserRole userRole : userRoleList) {
            Example roleMenuExp = new Example(RoleMenu.class);
            roleMenuExp.createCriteria().andEqualTo("rid", userRole.getRid());
            List<RoleMenu> roleMenuList = roleMenuMapper.selectByExample(roleMenuExp);
            if (!ObjectUtils.isEmpty(roleMenuList)) {
                //查询菜单信息 - 第一层
                List<Map<String, Object>> label = new ArrayList<Map<String, Object>>();
                for (RoleMenu roleMenu : roleMenuList) {
                    Map<String, Object> map = menuMapper.selectOneById(roleMenu.getMid(), systype);
                    if (map != null) {
                        label.add(map);
                    }
                }
                //遍历1级菜单查询下层菜单
                for (Map<String, Object> map : label) {
                    //查询下层菜单
                    Long id = (Long) map.get("id");
                    findNextLever(map, id, systype, userRole.getRid());
                }
                resultList.addAll(label);
            }

        }
        LinkedHashSet<Map<String, Object>> hashSet = new LinkedHashSet<>(resultList);
        ArrayList<Map<String, Object>> listWithoutDuplicates = new ArrayList<Map<String, Object>>(hashSet);
        List<Map<String, Object>> returnList = compareById(listWithoutDuplicates);
        return new Result<User>(true, StatusCode.OK, "查询成功！", returnList);
    }

    public List<Map<String, Object>> compareById(List<Map<String, Object>> list) {
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> frontMap, Map<String, Object> nextMap) {
                String front = String.valueOf(frontMap.get("id"));
                String next = String.valueOf(nextMap.get("id"));
                return front.compareTo(next);
            }
        });
        return list;
    }

    public void findNextLever(Map<String, Object> map, Long parentId, String sysType, Long rid) {
        List<Map<String, Object>> menuList = menuMapper.findMenuListByPid(parentId, sysType, rid);
        if (!ObjectUtils.isEmpty(menuList)) {
            map.put("children", menuList);
            for (Map<String, Object> childrenMap : menuList) {
                findNextLever(childrenMap, (Long) childrenMap.get("id"), sysType, rid);
            }
        }
    }

    /**
     * 分页获取菜单
     *
     * @param del
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Result getMenus(String del, String stid, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        Example example = new Example(Menu.class);
        if (!StringUtils.isEmpty(del)) {
            example.createCriteria().andEqualTo("del", del);
        }
        if (!StringUtils.isEmpty(stid)) {
            example.and(example.createCriteria().andEqualTo("stid", stid));
        }
        List<Menu> list = menuMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(list)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "暂无数据");
        }
        for (Menu menu : list) {
            Example sysExp = new Example(SysType.class);
            sysExp.createCriteria().andEqualTo("id", menu.getStid());
            SysType sysType = sysTypeMapper.selectOneByExample(sysExp);
            menu.setSysName(sysType.getSysName());
            Example acctExp = new Example(Account.class);
            acctExp.createCriteria().andEqualTo("id", menu.getAcctid());
            Account account = accountMapper.selectOneByExample(acctExp);
            menu.setAcctName(account.getAcctname());
        }
        PageInfo<Menu> pageInfo = new PageInfo<>(list);
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    /**
     * 添加菜单
     *
     * @param menu
     * @return
     */
    @Override
    public Result addMenu(Menu menu) {
        int res = menuMapper.insertSelective(menu);
        if (res == 0) {
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /**
     * 修改菜单
     *
     * @param menu
     * @return
     */
    @Override
    public Result updateMenu(Menu menu) {
        int res = menuMapper.updateByPrimaryKeySelective(menu);
        if (res == 0) {
            return new Result(false, StatusCode.ERROR, "修改失败");
        }
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除菜单
     *
     * @param id
     * @return
     */
    @Override
    public Result delMenu(Long id) {
        Example example = new Example(RoleMenu.class);
        example.createCriteria().andEqualTo("mid", id);
        List<RoleMenu> list = roleMenuMapper.selectByExample(example);
        if(!ObjectUtils.isEmpty(list)){
            return new Result(false,StatusCode.ERROR,"禁止删除,正在使用");
        }
        int res = menuMapper.deleteByPrimaryKey(id);
        if(res == 0){
            return new Result(false,StatusCode.ERROR,"删除失败");
        }
        return new Result(true, StatusCode.OK, "删除成功");
    }

    /**
     * 添加菜单
     *
     * @param menuDao
     * @return
     */
    @Override
    public Result inserMenu(MenuDao menuDao) {
        int res = menuMapper.insertMenu(menuDao.getStid(), menuDao.getAcctid(), menuDao.getList());
        if (res == 0) {
            return new Result(false, StatusCode.ERROR, "添加失败");
        }
        return new Result(true, StatusCode.OK, "添加成功");
    }

    /**
     * 条件查询
     * @param stid
     * @param acctid
     * @return
     */
    @Override
    public Result getParentMenusByStid(String stid, Long acctid) {
        Example example = new Example(Menu.class);
        example.createCriteria().andIsNull("parentid");
        example.and(example.createCriteria().andEqualTo("stid", stid));
        example.and(example.createCriteria().andEqualTo("acctid", acctid));
        List<Menu> list = menuMapper.selectByExample(example);
        if (ObjectUtils.isEmpty(list)) {
            return new Result(false, StatusCode.NOTFOUNDERROR, "查无数据");
        }
        return new Result(true, StatusCode.OK, "查询成功", list);
    }

}
